# __author__ = 'heyin'
# __date__ = '2018/11/12 16:51'
# 下载股票数据
import time
import os
import json
import numpy as np
import pandas as pd
import requests
from pyecharts import Kline, Line, Overlap

from time_converison import timestamp2date

"""
希望用于计算的特征有：
开盘价，收盘价，最高点，最低点，成交量，涨跌幅度，换手率，K，D，J

特征处理：

目标值：
第二天是否上涨，以0表示跌，1表示涨
"""


# 'https://query1.finance.yahoo.com/v8/finance/chart/%5EIXIC?symbol=%5EIXIC&period1=34592400&period2=1541687400&interval=1d&includePrePost=true&events=div%7Csplit%7Cearn&lang=en-US&region=US&crumb=hetGgO9bB.x&corsDomain=finance.yahoo.com')
# 所有时间跨度的数据url：'https://query1.finance.yahoo.com/v8/finance/chart/%5EIXIC?symbol=%5EIXIC&period1=34592400&period2=1541687400&interval=1d')
# https://query1.finance.yahoo.com/v8/finance/chart/BABA?symbol=BABA&interval=1d
def yahoo(stock):
    """从雅虎股票获取数据"""
    # 构造首次请求url，用以获取首次交易的时间
    first_url = 'https://query1.finance.yahoo.com/v8/finance/chart/{}?symbol={}&interval=1d'.format(stock, stock)
    print(first_url)
    first_resp = requests.get(first_url).content.decode('utf-8')
    if json.loads(first_resp).get('chart').get('result') == 'null':
        error = json.loads(first_resp).get('chart').get('error').get('description')
        print(error)
        return
    first_trade_date = json.loads(first_resp).get('chart').get('result')[0].get('meta').get('firstTradeDate')
    # 构造请求所有数据的url
    all_url = 'https://query1.finance.yahoo.com/v8/finance/chart/{}?symbol={}&period1={}&period2={}&interval=1d'.format(
        stock, stock, first_trade_date, int(time.time()))
    print(all_url)
    all_resp = requests.get(all_url).content.decode('utf-8')

    result = json.loads(all_resp).get('chart').get('result')[0]
    meta = result.get('meta')
    timestamp = result.get('timestamp')  # 从北京时间 1971-2-5 22:30 开始  到现今每天的同一时刻。注意此为开盘时间
    quote = result.get('indicators').get('quote')[0]

    # 时间戳转为具体日期
    date_ = list()
    for t in timestamp:
        date_.append(timestamp2date(t))

    # 有些数据是null，python获取到的是None，需要处理
    # TODO 等pandas搞熟悉，使用pandas重新处理此数据

    high = quote.get('high')
    low = quote.get('low')
    open_ = quote.get('open')
    close = quote.get('close')
    volume = quote.get('volume')  # 2462430000  24亿  写入原始数据，需要的时候自行处理

    day_data = np.array([open_, close, low, high], dtype=np.float64)
    # 将None替换为nan
    day_data[day_data == None] = np.nan

    day_data = day_data.T
    day_data = np.around(day_data, 3)

    date_ = np.array(date_).reshape((day_data.shape[0], 1))
    volume = np.array(volume).reshape((day_data.shape[0], 1))
    day_data = np.hstack((np.array(date_), day_data, np.array(volume)))

    # 写入文件
    pd_data = pd.DataFrame(day_data, columns=['date', 'open', 'close', 'low', 'high', 'volume'])
    # 创建存储股票的文件夹
    if not os.path.exists('./stockdata/'):
        os.mkdir('./stockdata')
    file_path = './stockdata/{}.csv'.format(stock)
    pd_data.to_csv(file_path, header=True, index=False)
    print('数据已写入 {} 文件内'.format(file_path))


def moving_avg(file_path: str, file_name: str, ma_list=[20, 60, 120, 200]):
    """计算简单移动平均线"""
    # ma_list = [20, 60, 200]  # 计算多少天的均线
    if not file_path.endswith('/'):
        file_path = file_path + '/'
    stock_data = pd.read_csv('%s%s' % (file_path, file_name), parse_dates=[1])
    # stock_data.sort_values('date', inplace=True)
    for ma in ma_list:
        # stock_data['MA_' + str(ma)] = pd.rolling(stock_data['close'], ma)
        stock_data['MA_' + str(ma)] = stock_data['close'].rolling(ma).mean().round(2)
    print(stock_data)
    stock_data.to_csv('%sma_%s' % (file_path, file_name), index=False)


def first_strategy():
    """上穿某个均线买入，跌穿某个均线卖出"""
    stock_data = pd.read_csv('./stockdata/ma_^IXIC.csv').set_index('date', drop=True).loc['2008-12-23':,
                 ['open', 'close', 'MA_200']]
    # print(stock_data)
    isbuy = False  # 是否买入
    yes_dopen, yes_close, yes_date, yes_ma200 = None, None, None, None  # 变量保存昨日信息，用以均线比较计算
    buy_price = None  # 买入价
    shouyi = list()
    for index, data in stock_data.iterrows():
        ma200 = data['MA_200']
        dopen = data['open']
        close = data['close']
        if all([yes_dopen, yes_close, yes_date, yes_ma200]):
            if yes_close < yes_ma200 and close > ma200 and isbuy is False:
                print(index, dopen, close, ma200, '上穿120均线，买入', '买入价%s' % close)
                buy_price = close
                isbuy = True
            elif yes_close > yes_ma200 and close < ma200 and isbuy is True:
                print(index, dopen, close, ma200, '下穿120均线，卖出', '卖出价%s' % close)
                isbuy = False
                diff_price = round((close - buy_price) / buy_price, 2)
                shouyi.append(diff_price)
        yes_dopen, yes_close, yes_date, yes_ma200 = dopen, close, index, ma200
    print(shouyi)
    return shouyi


def shouyi(shouyi: list):
    a = 0
    b = 0
    alist = list()
    blist = list()
    init_money = 10000
    for i in shouyi:
        init_money = init_money * (1 + i)
        # if i >= 0:
        #     print('正收益')
        #     a += 1
        #     alist.append(i)
        # else:
        #     print('负收益')
        #     b += 1
        #     blist.append(i)
    # qiuhe = sum(shouyi)
    # print(qiuhe)
    # print('正收益次数%s，合计正收益%s' % (a, sum(alist)))
    # print('负收益次数%s，合计负收益%s' % (b, sum(blist)))
    print(init_money)


def kline():
    """绘制k线图，没什么用大概"""
    stock_data = pd.read_csv('./stockdata/ma.csv')
    kline = Kline("K 线图示例")
    # print(stock_data.loc[:, 'open':'high'].values)
    kline.add("日K", stock_data['date'].tolist(), stock_data.loc[:, 'open':'high'].values, is_datazoom_show=True,
              datazoom_type='both')
    maline = Line()
    print(stock_data.columns.values[-3:])
    for ma_name in stock_data.columns.values[-3:]:
        maline.add(ma_name, stock_data['date'].tolist(), stock_data[ma_name].values, is_datazoom_show=True,
                   datazoom_type='both')
    # overlap 用来叠加多个图在一个图内
    overlap = Overlap(width=1400, height=600)
    overlap.add(kline)
    overlap.add(maline)
    overlap.render(path='./nasdaq.html')

    # kline.render(path='./nasdaq.html')


if __name__ == '__main__':
    # yahoo('AAPL')
    # yahoo('^IXIC')
    # moving_avg('./stockdata', '^IXIC.csv')
    # kline()
    shou = first_strategy()
    shouyi(shou)
